<template>
  <el-dialog
    :model-value="dialogVisible"
    title="添加用户"
    width="40%"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" label-width="70px" :rules="rules">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="form.userName" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, ref } from 'vue'
import { adduser } from '@/api/captain'
import { ElMessage } from 'element-plus'
const emits = defineEmits(['update:modelValue', 'inituserlist'])
const formRef = ref(null)
const form = ref({
  userName: '',
  password: '',
  role: 2,
  status: 1
})
const handleClose = async () => {
  emits('update:modelValue', false)
}

const handleConfirm = () => {
  console.log(form.value)
  formRef.value.validate(async (valid) => {
    if (valid) {
      ElMessage({
        message: '用户添加成功',
        type: 'success'
      })
      await adduser(form.value)
      emits('inituserlist')
    } else {
      ElMessage({
        message: '用户添加失败',
        type: 'warning'
      })
      return false
    }
  })

  handleClose()
}
const rules = ref({
  username: [
    { required: true, message: '请输入有效用户名', trigger: 'blur' },
    { min: 3, max: 15, message: 'Length should be 3 to 5', trigger: 'blur' }
  ],
  password: [
    {
      required: true,
      message: '请输入有效密码',
      trigger: 'change'
    }
  ]
})
</script>

<style lang="scss" scoped></style>
